using Godot;

public partial class MainMenu : CanvasLayer
{
    [Export] public PackedScene SaveSlotPrefab; // 拖入 SaveSlotUI.tscn

    // UI 引用
    [Export] public Window SaveWindow;
    [Export] public Control SlotContainer; // ScrollContainer下的VBox
    [Export] public LineEdit NameInput;

    [Export] public Button BtnStart;
    [Export] public Button BtnQuit;
    [Export] public Button BtnNewGame;
    [Export] public Button BtnCloseWindow;

    [ExportGroup("Music")]
    // 背景音乐资源路径
    [Export]
    public string BGM_res;

    public override void _Ready()
    {
        // 主界面按钮
        BtnStart.Pressed += () =>
        {
            SaveWindow.PopupCentered(); // 显示存档窗口
            RefreshSaveList();
        };
        BtnQuit.Pressed += () => GetTree().Quit();

        // 存档窗口按钮
        BtnNewGame.Pressed += OnNewGamePressed;
        BtnCloseWindow.Pressed += () => SaveWindow.Hide();

        SaveWindow.Hide(); // 初始隐藏

        //BGM>.<
        AudioManager.Instance.PlayMusic(BGM_res);

    }

    public void RefreshSaveList()
    {
        // 1. 清空旧列表
        foreach (Node child in SlotContainer.GetChildren())
        {
            child.QueueFree();
        }

        // 2. 获取所有存档
        var saves = SaveSystem.GetAllSaves();

        // 3. 生成新列表
        foreach (var save in saves)
        {
            var slot = SaveSlotPrefab.Instantiate<SaveSlotUI>();
            SlotContainer.AddChild(slot);
            slot.Setup(save, this); // 传入数据和自身引用
        }
    }

    private void OnNewGamePressed()
    {
        string name = NameInput.Text.Trim();
        if (string.IsNullOrEmpty(name))
        {
            GD.Print("请输入存档名！"); // 可以换成 UI 提示
            return;
        }

        // 创建新存档并直接开始
        GameManager.Instance.NewGame(name);
    }
}